package com.note.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.text.Document;

public class ConsoleTextArea extends JTextArea {
    public ConsoleTextArea(InputStream[] inStreams) {
        for (int i = 0; i < inStreams.length; i++)
            startConsoleReaderThread(inStreams[i]);
    }

    public ConsoleTextArea(String text) throws IOException {
        super(text);
        LoopedStreams ls = new LoopedStreams();
        PrintStream ps = new PrintStream(ls.getOutputStream());
        System.setOut(ps);
        System.setErr(ps);
        startConsoleReaderThread(ls.getInputStream());
    }

    private void startConsoleReaderThread(InputStream inStream) {
        final BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
        (new Thread(new Runnable() {
            public void run() {
                StringBuffer sb = new StringBuffer();
                try {
                    Document doc = ConsoleTextArea.this.getDocument();
                    String s;
                    while ((s = br.readLine()) != null) {
                        boolean caretAtEnd = false;
                        caretAtEnd = (ConsoleTextArea.this.getCaretPosition() == doc.getLength());
                        sb.setLength(0);
                        ConsoleTextArea.this.append(sb.append(s).append('\n').toString());
                        if (caretAtEnd)
                            ConsoleTextArea.this.setCaretPosition(doc.getLength());
                    }
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, "BufferedReader read exception："+ e);
                            System.exit(1);
                }
            }
        })).start();
    }
}
